<template>
  <div>
    <el-container>
      <el-main>
        <el-form :inline="true" :model="groupCollectionPage">
          <el-form-item label="关键字" prop="keyword">
            <el-input v-model="groupCollectionPage.keyword" placeholder="关键字" @keyup.enter.native="search"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="isActive">
            <el-select v-model="groupCollectionPage.isActive" placeholder="状态" @change="selectChange">
              <el-option label="全部" :value="''"></el-option>
              <el-option label="生效" :value="true"></el-option>
              <el-option label="失效" :value="false"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="search" type="primary">查询</el-button>
          </el-form-item>
          <el-button type="primary" @click="dialogFormVisible = true">添加群库</el-button>
        </el-form>
        <!-- <el-button type="primary">编辑</el-button> -->
        <el-table :data="groupCollectionList" style="width: 100%">
          <el-table-column label="名字" prop="name"></el-table-column>
          <el-table-column label="描述" prop="description"></el-table-column>
          <el-table-column label="公众号" prop="accountResponse.publicAccountNickname"></el-table-column>
          <el-table-column label="创建时间" prop="createdTime">
            <template slot-scope="scope">
              {{formatTime(scope.row.createdTime)}}
            </template>
          </el-table-column>
          <el-table-column label="是否参与资源兑换" prop="isJoinResourceExchange">
            <template slot-scope="scope">
              {{ scope.row.isJoinResourceExchange ? '参与' : '不参与' }}
            </template>
          </el-table-column>
          <el-table-column label="非静默授权">
            <template slot-scope="scope">
              {{ scope.row.isWxInfo==1 ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column label="分流" prop="branch"></el-table-column>
          <el-table-column label="appIdKey" prop="appTopKey"></el-table-column>
          <el-table-column label="过期时长（天）" prop="expireLength"></el-table-column>
          <el-table-column label="状态" prop="branch">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.isActive" active-color="#13ce66" inactive-color="#ebebeb" @change="changeIsActive(scope.row.id, scope.row.isActive)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="270">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="showDetail(scope.row.id)">预览</el-button>
              <el-button type="text" size="small" @click="copyLink(scope.row.address)">复制地址</el-button>
              <el-button type="text" size="small" @click="copyLink(scope.row.dynamicAddress)" v-if="false">动态地址</el-button>
              <span> | </span>
              <el-button type="text" size="small" @click="editGC(scope.row.id)">编辑</el-button>
              <el-button @click="goGroup(scope.row.id)" type="text" size="small">群管理</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="page">
        <el-pagination
          background
          @size-change="handlePageSizeChange"
          @current-change="handleCurrentPageChange"
          :current-page="this.groupCollectionPage.page + 1"
          :page-sizes="[10, 20, 100, 300, 400]"
          :page-size="20"
          layout="total, sizes, prev, pager, next, jumper"
          :total="this.groupCollectionPage.totalElement">
        </el-pagination>
      </div>
      </el-main>
      <!-- 新增群库 -->
      <el-dialog title="新增群库" :visible.sync="dialogFormVisible" top="13vh">
        <el-form :model="groupCollection" :rules="rules" ref="groupCollection">
          <el-form-item label="群库名称" :label-width="formLabelWidth" prop="name">
            <el-input v-model="groupCollection.name" auto-complete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="群库描述" :label-width="formLabelWidth" prop="description">
            <el-input v-model="groupCollection.description" auto-complete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="群库微信" :label-width="formLabelWidth" prop="groupCollectionWechatId">
            <el-input v-model="groupCollection.groupCollectionWechatId" auto-complete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="分流" :label-width="formLabelWidth" prop="branch">
            <el-input v-model.number="groupCollection.branch" auto-complete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="公众号" :label-width="formLabelWidth" prop="appId">
            <el-select v-model="groupCollection.appId" placeholder="选择公众号" @change="isqu">
              <el-option v-for="item in defaultPublicAccount" :key="item.appId" :label="item.publicAccountNickname" :value="item.appId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="isquappid" label="appIdKey" :label-width="formLabelWidth" prop="appTopKey">
            <el-input v-model="groupCollection.appTopKey" auto-complete="off" clearable></el-input>
          </el-form-item>
          <el-form-item v-if="isquappid" label="过期时长（天）" :label-width="formLabelWidth" prop="expireLength">
            <el-input v-model="groupCollection.expireLength" auto-complete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="群库状态" :label-width="formLabelWidth" prop="isActive">
            <el-switch v-model="groupCollection.isActive" active-color="#13ce66" inactive-color="#ebebeb"></el-switch>
          </el-form-item>
          <el-form-item label="是否参与资源兑换" :label-width="formLabelWidth" prop="isJoinResourceExchange">
            <el-switch v-model="groupCollection.isJoinResourceExchange" active-color="#13ce66" inactive-color="#ebebeb"></el-switch>
          </el-form-item>
          <el-form-item label="非静默授权" :label-width="formLabelWidth" prop="isWxInfo">
            <el-switch v-model="groupCollection.isWxInfo2" active-color="#13ce66" inactive-color="#ebebeb"></el-switch>
          </el-form-item>
          <el-form-item
            v-for="(linkMan, index) in groupCollection.linkMans"
            :label="'联系人' + (index + 1)"
            :label-width="formLabelWidth"
            :key="index"
            :prop="'linkMans.' + index + '.value'"
          >
            <el-col :span="21"><el-input v-model="linkMan.value"></el-input></el-col>
            <el-col :span="2" :offset="1"><el-button @click.prevent="removeLinkMan(linkMan)" type="danger" icon="el-icon-delete" circle></el-button></el-col>
          </el-form-item>
          <el-form-item label="联系人" :label-width="formLabelWidth">
            <el-button :disabled="addDisable" @click="addLinkMan"  type="primary" icon="el-icon-plus" circle></el-button>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="close('groupCollection')">取 消</el-button>
          <el-button type="primary" @click="formSubmit" :disabled="isDisabled">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 修改群库 -->
      <el-dialog title="编辑群库" :visible.sync="editDialogFormVisible" top="13vh">
        <el-form :model="editGroupCollection" :rules="rules" ref="editGroupCollection">
          <el-form-item label="群库名称" :label-width="formLabelWidth" prop="name">
            <el-input v-model="editGroupCollection.name" auto-complete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="群库描述" :label-width="formLabelWidth" prop="description">
            <el-input v-model="editGroupCollection.description" auto-complete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="群库微信" :label-width="formLabelWidth" prop="groupCollectionWechatId">
            <el-input v-model="editGroupCollection.groupCollectionWechatId" auto-complete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="分流" :label-width="formLabelWidth" prop="branch">
            <el-input v-model.number="editGroupCollection.branch" auto-complete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="公众号" :label-width="formLabelWidth" prop="appId">
            <el-select v-model="editGroupCollection.appId" placeholder="选择公众号" disabled="disabled">
              <el-option v-for="item in defaultPublicAccount" :key="item.appId" :label="item.publicAccountNickname" :value="item.appId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="isquappidupdate" label="appIdKey" :label-width="formLabelWidth" prop="appTopKey">
            <el-input v-model="editGroupCollection.appTopKey" auto-complete="off" clearable></el-input>
          </el-form-item>
          <el-form-item v-if="isquappidupdate" label="过期时长（天）" :label-width="formLabelWidth" prop="expireLength">
            <el-input v-model="editGroupCollection.expireLength" auto-complete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="状态" :label-width="formLabelWidth" prop="isActive">
            <el-switch v-model="editGroupCollection.isActive" active-color="#13ce66" inactive-color="#ebebeb"></el-switch>
          </el-form-item>
          <el-form-item label="是否参与资源兑换" :label-width="formLabelWidth" prop="isJoinResourceExchange">
            <el-switch v-model="editGroupCollection.isJoinResourceExchange" active-color="#13ce66" inactive-color="#ebebeb"></el-switch>
          </el-form-item>
          <el-form-item label="非静默授权" :label-width="formLabelWidth" prop="isWxInfo">
            <el-switch v-model="editGroupCollection.isWxInfo2" active-color="#13ce66" inactive-color="#ebebeb"></el-switch>
          </el-form-item>
          <el-form-item
            v-for="(linkMan, index) in editGroupCollection.linkMans"
            :label="'联系人' + (index + 1)"
            :label-width="formLabelWidth"
            :key="index"
            :prop="'linkMans.' + index + '.value'"
          >
            <el-col :span="21"><el-input v-model="linkMan.value"></el-input></el-col>
            <el-col :span="2" :offset="1"><el-button @click.prevent="removeLinkManEdit(linkMan)" type="danger" icon="el-icon-delete" circle></el-button></el-col>
          </el-form-item>
          <el-form-item label="联系人" :label-width="formLabelWidth">
            <el-button :disabled="addDisableEdit" @click="addLinkManEdit"  type="primary" icon="el-icon-plus" circle></el-button>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="close('editGroupCollection')">取 消</el-button>
          <el-button type="primary" @click="editSubmit" :disabled="isDisabled">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 群库预览 -->
      <div ref="codeContent" v-show="false">
        <div style="text-align: center;">
          <canvas ref="qrcode"></canvas>
        </div>
        <el-form :model="gcDetail" label-width="40px" :inline="true">
          <el-form-item prop="address" label="url">
            <el-input v-model="gcDetail.address" disabled="disabled"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="copyLink(gcDetail.address)">复制</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-container>
  </div>
</template>

<script>
import moment from 'moment';
// import QRCode from 'qrcode';
import QrCode from './qrCode.vue';
import util from '../../util/index';

export default {
  data() {
    /* eslint-disable */
    const checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'));
      } else {
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
        if (reg.test(value)) {
          callback();
        } else {
          return callback(new Error('请输入正确的手机号'));
        }
      }
    };
    return {
      isquappid: false,
      isquappidupdate: false,
      isDisabled: false,
      addDisable: false,
      addDisableEdit: false,
      key: 1,
      editDialogFormVisible: false,
      dialogDetail: false,
      editGroupCollection: {
        name: '',
        description: '',
        imageData: '',
        groupCollectionWechatId: '',
        branch: '',
        appId: '',
        isActive: true,
        isJoinResourceExchange: false,
        isWxInfo: 0,
        isWxInfo2: false,
        mobiles: '',
        linkMans: [],
        appTopKey: '',
        expireLength: ''
      },
      gcDetail: {
        address: '',
      },
      dialogImageUrl: '',
      dialogFormVisible: false,
      dialogVisible: false,
      formLabelWidth: '110px',
      defaultPublicAccount: [],
      groupCollection: {
        name: '',
        description: '',
        imageData: '',
        groupCollectionWechatId: '',
        branch: '',
        appId: '',
        isActive: true,
        isJoinResourceExchange: false,
        isWxInfo: 0,
        isWxInfo2: false,
        mobiles: '',
        linkMans: [],
        appTopKey: '',
        expireLength: ''

      },
      rules: {
        name: [{
          required: true, message: '请输入群库名称，最大30个汉字', trigger: 'blur', max: 30,
        }],
        description: [{
          required: true, message: '请输入群库名称，最大30个汉字', trigger: 'blur', max: 30,
        }],
        groupCollectionWechatId: [{
          required: true, message: '请输入微信号，最大30个汉字', trigger: 'blur', max: 30,
        }],
        branch: [{
          required: true, type: 'number', message: '请输入分流数（1～999）的整数，若填写1，表示无分流', trigger: 'blur', min: 1,
        }],
        appId: [{ required: true, message: '请选择公众号', trigger: 'blur' }],
        isActive: [{ required: true, message: '请选择状态', trigger: 'blur' }],
        isJoinResourceExchange: [{ required: true, message: '请选择是否参与资源兑换', trigger: 'blur' }],
        'linkMans.0.value': [{ validator: checkPhone, trigger: 'blur' }],
        'linkMans.1.value': [{ validator: checkPhone, trigger: 'blur' }],
        'linkMans.2.value': [{ validator: checkPhone, trigger: 'blur' }],
        'linkMans.3.value': [{ validator: checkPhone, trigger: 'blur' }],
        'linkMans.4.value': [{ validator: checkPhone, trigger: 'blur' }],
      },
      groupCollectionPage: {
        page: 0,
        size: 20,
        keyword: '',
        isActive: '',
        totalElement: 1,
      },
    };
  },
  mounted() {
    this.$store.dispatch('getGroupCollection', this.groupCollectionPage).then((res) => {
      this.groupCollectionPage.totalElement = res.page.totalElement;
    });
    this.$store.dispatch('getPublicAccountsWithDefault', this.defaultPublicAccount).then((res) => {
      const defaultAppId = res.filter(item => item.publicAccountNickname === '默认公众账号');
      this.defaultPublicAccount = res;
      this.groupCollection.appId = defaultAppId;
    });
  },
  computed: {
    groupCollectionList() {
      return this.$store.state.group.groupCollectionList;
    },
  },
  methods: {
    // 新增
    isqu(appid) {
      const env = process.env.NODE_ENV || 'development';
      let quappid = 'wx8daa03cd7585741c'
      if (env === 'production') {
        quappid = 'wx71a3f7ff21eb38fe'
      }
      if (appid === quappid) {
        this.isquappid = true
      } else {
        this.isquappid = false
      }
    },
    // 删除联系人
    removeLinkMan(item) {
      const index = this.groupCollection.linkMans.indexOf(item);
      if (index !== -1) {
        this.groupCollection.linkMans.splice(index, 1);
      }
      this.addDisable = false;
    },
    // 新增联系人
    addLinkMan() {
      this.groupCollection.linkMans.push({
        value: '',
      });
      if (this.groupCollection.linkMans.length >= 5) {
        this.addDisable = true;
      }
    },
    // 编辑
    // 删除联系人
    removeLinkManEdit(item) {
      const index = this.editGroupCollection.linkMans.indexOf(item);
      if (index !== -1) {
        this.editGroupCollection.linkMans.splice(index, 1);
      }
      this.addDisableEdit = false;
    },
    // 新增联系人
    addLinkManEdit() {
      this.editGroupCollection.linkMans.push({
        value: '',
      });
      if (this.editGroupCollection.linkMans.length >= 5) {
        this.addDisableEdit = true;
      }
    },
    // 更改列表状态
    changeIsActive(groupCollectionId, isActive) {
      const param = {
        groupCollectionId,
        isActive,
      };
      this.$store.dispatch('changeGroupCollectionActive', param).then(() => {
        this.$message({
          type: 'success',
          message: '更改状态成功',
        });
      });
    },
    handlePageSizeChange(size) {
      this.groupCollectionPage.size = size;
      this.$store.dispatch('getGroupCollection', this.groupCollectionPage).then((res) => {
        this.groupCollectionPage.totalElement = res.page.totalElement;
      });
    },
    handleCurrentPageChange(page) {
      this.groupCollectionPage.page = page - 1;
      this.$store.dispatch('getGroupCollection', this.groupCollectionPage).then((res) => {
        this.groupCollectionPage.totalElement = res.page.totalElement;
      });
    },
    selectChange(val) {
      this.groupCollectionPage.isActive = val;
    },
    formatTime(stamp) {
      return stamp ? moment(stamp).format('YYYY-MM-DD HH:mm:ss') : '立即推送';
    },
    editGC(id) {
      const param = {
        groupCollectionId: id,
      };
      this.$store.dispatch('getGroupCollectionDetail', param).then((res) => {
        /* eslint-disable */
        let linkManArr = [] , mobileArr = [];
        if(res.mobiles) {
          mobileArr = res.mobiles.split(',');
        }
        mobileArr.map((item)=>{
          linkManArr.push({value:item})
        })
        this.editDialogFormVisible = true;
        this.dialogImageUrl = res.imageData;
        this.editGroupCollection = Object.assign(
          {},
          {
            isWxInfo2:  res.isWxInfo==1,
            name: res.name,
            description: res.description,
            imageData: res.imageData,
            groupCollectionWechatId: res.groupCollectionWechatId,
            branch: res.branch,
            appId: res.accountResponse.appId,
            isActive: res.isActive,
            isJoinResourceExchange: res.isJoinResourceExchange,
            groupCollectionId: id,
            linkMans: linkManArr,
            mobiles: res.mobiles,
            expireLength: res.expireLength,
            appTopKey: res.appTopKey,
          },
        );
        const env = process.env.NODE_ENV || 'development';
        let quappid = 'wx8daa03cd7585741c'
        if (env === 'production') {
          quappid = 'wx71a3f7ff21eb38fe';
        };
        if (this.editGroupCollection.appId === quappid) {
          this.isquappidupdate = true;
        } else {
          this.isquappidupdate = false;
        }
        if (this.editGroupCollection.linkMans.length >= 5) {
          this.addDisableEdit = true;
        } else {
          this.addDisableEdit = false;
        }
      });
    },
    showDetail(id) {
      const param = {
        groupCollectionId: id,
      };
      this.$store.dispatch('getGroupCollectionDetail', param).then((res) => {
        this.dialogDetail = true;
        this.gcDetail.address = res.address;
        this.$msgbox({
          title: '群库预览',
          showConfirmButton: false,
          message: this.$createElement(QrCode, {
            key: this.key + 1,
            props: {
              address: res.address,
            },
          }),
        });
        // setTimeout(this.createQRCode, 1000);
      });
    },
    copyLink(link) {
      const input = document.createElement('input');
      document.body.appendChild(input);
      input.setAttribute('value', link);
      input.select();
      if (document.execCommand('copy')) {
        document.execCommand('copy');
        this.$message({
          type: 'success',
          message: '复制成功!',
        });
        console.log('复制成功');
      }
      document.body.removeChild(input);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleConverting(...arg) {
      console.log(arg);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handleExceed() {
      this.$message.warning('请先删除原来的头像图片');
    },
    imageConvertoBase64(file) {
      util
        .imageConvertoBase64(file)
        .then((base64) => {
          this.groupCollection.imageData = base64;
          this.editGroupCollection.imageData = base64;
          this.dialogImageUrl = base64;
        })
        .catch((e) => {
          console.log('convert to base64 error .', e);
        });
    },
    goGroup(groupCollectionId) {
      this.$router.push({
        path: `/group/${groupCollectionId}`,
      });
    },
    search() {
      const param = {
        page: 0,
        size: this.groupCollectionPage.keyword ? this.groupCollectionPage.size : 20,
        isActive: this.groupCollectionPage.isActive,
        keyword: this.groupCollectionPage.keyword.trim(),
      };
      this.$store.dispatch('getGroupCollection', param).then((res) => {
        this.groupCollectionPage.page = res.page.currentPage + 1;
        this.groupCollectionPage.totalElement = res.page.totalElement;
        console.log(res);
      });
    },
    editSubmit() {
      /* eslint-disable */
      this.editGroupCollection.mobiles = '';
      this.editGroupCollection.linkMans.map((item, index) => {
        if(index >= this.editGroupCollection.linkMans.length-1){
          this.editGroupCollection.mobiles += item.value;
        }else{
          this.editGroupCollection.mobiles += item.value + ',';
        }
      })
      /* eslint-enable */
      this.$refs.editGroupCollection.validate().then(() => {
        this.editGroupCollection.isWxInfo = this.editGroupCollection.isWxInfo2?1:0
        this.isDisabled = true;
        this.$store.dispatch('editGroupCollectionDetail', this.editGroupCollection).then(() => {
          this.$message({
            type: 'success',
            message: '修改成功',
          });
          this.close('editGroupCollection');
          this.isDisabled = false;
          this.$store.dispatch('getGroupCollection', this.groupCollectionPage).then((res) => {
            this.groupCollectionPage.totalElement = res.page.totalElement;
            console.log(this.groupCollectionPage);
          });
        });
      });
    },
    formSubmit() {
      // const that = this;
      /* eslint-disable */

      this.groupCollection.linkMans.map((item, index) => {
        if(index >= this.groupCollection.linkMans.length-1){
          this.groupCollection.mobiles += item.value;
        }else{
          this.groupCollection.mobiles += item.value + ',';
        }
      })
      /* eslint-enable */
      this.$refs.groupCollection.validate().then(() => {
        this.groupCollection.isWxInfo = this.groupCollection.isWxInfo2?1:0;
        this.isDisabled = true;
        this.$store.dispatch('addGroupCollection', this.groupCollection).then(() => {
          this.$message({
            type: 'success',
            message: '新增成功',
          });
          this.close('groupCollection');
          this.isDisabled = false;
          // 获取新的数据
          this.$store.dispatch('getGroupCollection', this.groupCollectionPage).then((res) => {
            this.groupCollectionPage.totalElement = res.page.totalElement;
            console.log(this.groupCollectionPage);
          });
        });
      });
    },
    close(form) {
      this.$refs[form].resetFields();
      this.groupCollection.mobiles = '';
      this.editGroupCollection.mobiles = '';
      this.dialogFormVisible = false;
      this.editDialogFormVisible = false;
      this.dialogDetail = false;
    },
  },
};
</script>

<style lang="less" scoped>
.page {
  margin-top: 20px;
  text-align: right;
}
.avatar {
  width: 150px;
  height: 150px;
}
</style>

